<template>
  <div class="account-box">
    <!-- <button @click="$message({ type:'success', message:'提示' })">测试全局的方法</button> -->
    <!-- <button @click="aa">Vue2的选项API调用</button> -->
    <div class="toggle">
      <a href="javascript:;" v-if="isMsgLogin" @click="isMsgLogin=!isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="isMsgLogin=!isMsgLogin">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form ref="formCom" class="form" v-slot="{ errors }" :validation-schema="schema">
      <h2>表单校验失败提示：{{ errors }}</h2>
      <!-- 账号登录 -->
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field name="account" :class="{ error: errors.account }" v-model="form.account" type="text" placeholder="请输入用户名或手机号" />
          </div>
          <div class="error" v-if="errors.account"><i class="iconfont icon-warning" />{{errors.account}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field name="password" :class="{ error: errors.password }"  v-model="form.password" type="password" placeholder="请输入密码" />
          </div>
          <div class="error" v-if="errors.password"><i class="iconfont icon-warning" />{{errors.password}}</div>
        </div>
      </template>
      <!-- 短信登录 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input v-model="form.mobile" type="text" placeholder="请输入手机号" />
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input v-model="form.code" type="text" placeholder="请输入验证码">
            <span @click="sendCodeBtn" class="code">{{ time === 0 ? '发送验证码' : `${time}秒`}}</span>
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree"><i class="iconfont icon-warning" />{{errors.isAgree}}</div>
      </div>
      <a @click="loginBtn" href="javascript:;" class="btn">登录</a>
    </Form>
    <div class="action">
      <a href="https://graph.qq.com/oauth2.0/show?which=Login&display=pc&client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { userAccountLogin, userMobileLogin, userMobileLoginMsg } from '@/api/user'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { Message } from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/shared'

export default {
  name: 'LoginForm',
  components: { Form, Field },
  setup () {
    // 是否短信登录
    const isMsgLogin = ref(true)
    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    // 表单数据
    const form = reactive({
      account: '',
      password: '',
      mobile: '',
      code: '',
      isAgree: true
    })

    // 登录按钮
    // 可以用测试账号： sujiehao   密码： 123456
    const loginBtn = async () => {
      // 主动校验整个表单，返回表单校验结果(Promise对象)
      const bl = await formCom.value.validate()
      // console.log(bl)
      // 校验通过才发送请求
      if (bl) {
        try {
          let result
          if (isMsgLogin.value) {
            // 情况1：手机号码+短信验证码登录
            const res = await userMobileLogin(form)
            result = res.result
          } else {
            // 情况2：用户名+密码登录
            const res = await userAccountLogin(form)
            result = res.result
          }
          // console.log(result)
          // alert('登录成功')
          Message({ type: 'success', message: '登录成功' })
          store.commit('user/setUser', result)
          // 购物车商品合并
          store.dispatch('cart/mergeLocalCart')
          // 优先使用回跳地址，没有则跳转首页
          router.push(route.query.redirectUrl || '/')
        } catch (err) {
        // console.dir(err)
          // alert(err.response.data.message)
          Message({ type: 'error', message: err.response.data.message })
        }
      }
    }

    const formCom = ref(null)

    // 定时器倒计时业务
    const time = ref(0)
    const { resume, pause } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })

    // 点击发送验证码
    const sendCodeBtn = async () => {
      // 需要校验手机号
      const res = schema.mobile(form.mobile)
      // 💥手机号校验不通过，提示用户
      if (res !== true) return Message({ type: 'warn', message: res })
      // 倒计时没结束则退出，不做任何处理
      if (time.value !== 0) return
      try {
        // 发送请求
        await userMobileLoginMsg(form.mobile)
        // 请求发送成功提示
        Message({ type: 'success', message: '发送验证码成功' })
        // 秒数初始化
        time.value = 60 * 2
        // 倒计时开始
        resume()
      } catch (error) {
        console.dir(error)
        // 💥请求异常(验证码已发送/用户名不存在)，提示用户
        Message({ type: 'warn', message: error.response.data.message })
      }
    }

    return { isMsgLogin, form, loginBtn, schema, formCom, sendCodeBtn, time }
  }
  // 选项API的方式能通过 this.$message 调用
  // methods: {
  //   aa () {
  //     this.$message({ type: 'error', message: '错误提示' })
  //   }
  // }
}
</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
